<template>
  <div class="app-container">
    <div v-show="!isMaterialTag">
      <div>
        <div class="handle-box">
          <span style="padding-right: 10px">{{
            $t("tool.departmentName")
          }}</span>
          <treeselect
            v-model="deptValue"
            :placeholder="$t('operating.pleaseChosen')"
            :show-count="true"
            :max-height="600"
            :options="depData"
            :default-expand-level="1"
            style="width: 150px; margin-right: 10px"
            @input="nodeClick"
          />
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="addData"
          >{{ $t('common.caddkey') }}</el-button>
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="deleteAll"
          >
            {{ $t('common.cdelete') }}
          </el-button>

          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="reportAll"
          >
            {{ $t("operating.export") }}</el-button>
          <el-button
            type="info"
            plain
            icon="el-icon-s-operation"
            size="mini"
            @click="seachToolType"
          >{{ $t("tool.seachCarType") }}</el-button>
        </div>
      </div>

      <div>
        <!--表格-->
        <el-table
          ref="multipleTable"
          class="datalist"
          :data="tableData"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
        >
          <!--多选框-->
          <el-table-column
            type="selection"
            width="50"
            align="center"
          />
          <!--货物名字-->
          <el-table-column
            prop="name"
            :label="$t('tool.toolName')"
          />
          <!--货物类型-->
          <el-table-column
            prop="workTypeName"
            :label="$t('tool.toolType')"
          />
          <!-- 货物信息 -->
          <el-table-column
            prop="materialInfo"
            label="货物信息"
          />
          <!--货物编号-->
          <el-table-column
            prop="resourceId"
            :label="$t('tool.resourceId')"
          />
          <!--绑定标签-->
          <el-table-column
            prop="tagId"
            :label="$t('tool.tagId')"
          />
          <!--所在部门-->
          <el-table-column
            prop="departmentName"
            :label="$t('tool.departmentName')"
          />
          <!-- 在线状态 -->
          <el-table-column
            min-width="100"
            :label="$t('staff.onlineState')"
            prop="onlineState"
          >
            <template slot-scope="scope">
              <el-button
                icon="el-icon-check"
                :type="scope.row.onlineState === 1 ? 'success' : 'info'"
                circle
              />
            </template>
          </el-table-column>
          <!--操作-->
          <el-table-column :label="$t('operating.operating')" min-width="250">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
              >{{ $t("operating.handle") }}</el-button>
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.$index, scope.row)"
              >{{ $t("operating.delete") }}</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleFinalPosition(scope.$index, scope.row)"
              >{{ $t("operating.finalPosition") }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            :current-page="currentPage"
            :page-sizes="[10, 25, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="this.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!--编辑弹出框-->
      <el-dialog
        :title="titleMap[dialogStatus]"
        :close-on-click-modal="false"
        :visible.sync="editVisible"
        width="30%"
      >
        <el-form ref="form" :model="form" label-width="120px" :rules="rules">
          <!--部门-->
          <el-form-item
            :label="$t('tool.departmentName')"
            prop="depIdx"
            :rules="filter_rules({ required: '请选择' })"
          >
            <el-select
              v-model="form.depIdx"
              filterable
              :placeholder="$t('operating.pleaseChosen')"
            >
              <el-option
                v-for="item in deptSelect"
                :key="item.idx"
                :label="item.name"
                :value="item.idx"
              />
            </el-select>
          </el-form-item>
          <!--货物名称-->
          <el-form-item
            :label="$t('tool.toolName')"
            prop="name"
            :rules="filter_rules({ required: '请输入货物名称' })"
          >
            <el-input
              v-model="form.name"
              style="max-width: 215px"
              :placeholder="$t('operating.pleaseWrite')"
            />
          </el-form-item>
          <!--货物类型-->
          <!--<el-form-item label="货物类型" :rules="filter_rules({required:'请输入货物类型'})">-->
          <!--<el-input v-model="form.materialType" style="width: 215px;" :disabled="true" placeholder="请输入货物类型"></el-input>-->
          <!--</el-form-item>-->
          <!--货物信息-->
          <el-form-item
            :label="$t('tool.materialInfo')"
            :rules="filter_rules({ required: '请输入货物信息' })"
          >
            <el-input
              v-model="form.materialInfo"
              style="max-width: 215px"
              :placeholder="$t('operating.pleaseWrite')"
            />
          </el-form-item>
          <!--货物标签-->
          <el-form-item :label="$t('tool.tagId')">
            <el-input
              v-model="form.tagId"
              style="max-width: 215px"
              :placeholder="$t('operating.pleaseWrite')"
            />
          </el-form-item>
          <!--货物类型-->
          <el-form-item :label="$t('tool.toolType')">
            <el-select
              v-model="form.toolTypeId"
              filterable
              :placeholder="$t('operating.pleaseChosen')"
              style="max-width: 215px"
            >
              <el-option
                v-for="item in toolTypeList"
                :key="item.idx"
                :label="item.name"
                :value="item.idx"
              />
            </el-select>
          </el-form-item>
          <!--绑定标签-->
          <el-form-item
            :label="$t('tool.resourceId')"
            :rules="filter_rules({ required: '请输入货物RFID编号' })"
          >
            <el-input
              v-model="form.resourceId"
              style="max-width: 215px"
              :placeholder="$t('operating.pleaseWrite')"
            />
          </el-form-item>
        </el-form>
        <!--操作-->
        <span class="dialog-footer">
          <el-button @click="closeDialog()">{{
            $t("operating.cancel")
          }}</el-button>

          <el-button
            type="primary"
            class="edit_confirm"
            @click="saveStaffEdit('form')"
          >{{ $t("operating.determine") }}</el-button>
        </span>
      </el-dialog>

      <el-dialog
        :visible.sync="positionDialogVisible"
        width="50%"
        @open="openPosiotionDialogCallBack"
        @close="closePositionDialogCallBack"
      >
        <div id="map" style="width: 100%; height: 500px" />
      </el-dialog>
    </div>
    <div v-show="isMaterialTag">
      <materail-tag @changeTag="materialTag" />
    </div>
  </div>
</template>

<script>
import { baseUrl } from '@/utils/iMap.js'
import materialTag from './materialTag'
import {
  materialAll,
  resourceTypeAll,
  deptList,
  materailDelete,
  materialSaveEdit,
  materialTypeList,
  getDeptTree,
  downloadFile,
  getMap
} from '@/api/cy.js'
import Treeselect from '@riophae/vue-treeselect'
import Cookie from 'js-cookie'
import {
  Load_Map,
  TagStyle,
  _TransMetric,
  _TransPixel,
  _dPR,
  _iMap,
  setMapCenter
} from '@/utils/iMap.js'
import { Vector as VectorLayer } from 'ol/layer.js'
import { Vector } from 'ol/source.js'
import { Point } from 'ol/geom.js'
import Feature from 'ol/Feature.js'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: {
    Treeselect,
    'materail-tag': materialTag
  },
  data() {
    return {
      isMaterialTag: false, // 是否展示物料管理
      deptValue: null,
      searchValue: '', // 空字符，用于初始化输入框

      /** *******************表格相关*********************/
      tableHeight: 630,
      editEnable: true, // 点击的编辑or添加
      editVisible: false, // 编辑框是否可见
      editDeptVisible: false, // 编辑部门框是否可见
      delVisibleDept: false, // 部门树删除框是否可见
      editExportVisible: false, // 导入弹出框是否可见

      tableDataUrl: '../../json/tagtabledata.json', // 表格数据的地址
      tableData: [], // 表格模拟数据
      tableDataNum: 100,
      selectIndex: -1, // 选中的行
      multipleSelection: [], // 多选下标
      del_list: [], // 要批量删除的数据
      /** *******************表格相关*********************/
      currentPage: 1, // 当前所在页
      total: 0, // 总页数
      pageSize: '10', //
      // 用户表单提交
      rules: {}, // 用户表单验证
      form: { materialType: 'gl_material' },
      exportData: [
        { exportType: 0, label: '追加导入' },
        { exportType: 1, label: '覆盖导入' }
      ],
      file: new FormData(), // 导入文件
      departmentId: '', // 选中节点ID
      formExp: {},
      depData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      toolTypeList: [],
      deptForm: {},
      nodeName: '',
      parentId: 0,
      deptIdx: '',
      toolIdx: [],
      Idx: '',
      deptSelect: [],
      isActive: false, // 输入框是否禁用,
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        addEquipment: '添加',
        editEquipment: '编辑'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',

      positionDialogVisible: false,
      toolSource: null,
      toolLayer: null,
      rowData: null
    }
  },
  mounted() {
    //  已经完成模板渲染或者el对应的html渲染
    this.init()
  },
  methods: {
    closeDialog() {
      console.log('关闭接口')
    },
    materialTag() {
      this.isMaterialTag = false
    },
    init() {
      // 获取部门树数据
      this.getDeptList()
      // 获取车辆数据
      this.getToolList()
      this.getDept()
      this.getToolTypeList()

      this.setButtonStatus()
    },

    // 获取货物的最后位置
    handleFinalPosition(index, row) {
      this.rowData = row
      if (!this.rowData.hasOwnProperty('layerId')) {
        this.msgError('抱歉，缺少layerId值')
      } else {
        this.positionDialogVisible = true
      }
    },

    // 显示位置Dialog打开动画结束后的回调
    openPosiotionDialogCallBack() {
      const self = this
      // 根据地图中的层号获取地图参数
      getMap(parseInt(self.rowData.layerId))
        .then((result) => {
          const Res = result.data
          // 初始化地图
          Load_Map(
            baseUrl + RES.mapPath,
            RES.mapActualX,
            RES.mapActualY,
            RES.mapPixelX,
            RES.mapPixelY,
            RES.mapPixelX / RES.mapActualX,
            [RES.mapOriginX, RES.mapOriginY]
          )
          // 初始化容器
          self.initSource()
          // 添加位置点到地图中去
          const point = new Point(
            _TransPixel([self.rowData.posX, self.rowData.posY])
          )
          const feature = new Feature(point)
          self.toolSource.addFeature(feature)

          // 设置当前标签的位置居中显示
          setMapCenter(_TransPixel([self.rowData.posX, self.rowData.posY]))
        })
    },

    closePositionDialogCallBack() {
      this.releaseSource()
      _iMap.removeLayer(this.toolLayer)
      this.toolSource = null
      this.toolLayer = null
    },

    // 释放地图中的资源
    releaseSource() {
      if (this.toolSource != null) {
        const oldFeatures = this.toolSource.getFeatures() // 现在已有的标签数据
        let len = oldFeatures.length
        while (len > 0) {
          len--
          this.toolSource.removeFeature(oldFeatures[len])
          oldFeatures.splice(len, 1)
        }
      }
    },

    // 初始化位置容器
    initSource() {
      this.toolSource = new Vector({
        wrapX: false
      })

      this.toolLayer = new VectorLayer({
        minResolution: 0,
        maxResolution: _dPR * 2.4,
        source: this.toolSource,
        zIndex: 10000,
        renderBuffer: 100,
        updateWhileAnimating: true,
        updateWhileInteracting: true,
        style: function(feature, resolution) {
          return TagStyle(feature, resolution, -9999)
        }
      })

      _iMap.addLayer(this.toolLayer)
    },

    setButtonStatus() {
      // 判断是否为游客账号
      // let roleId = sessionStorage.getItem("roleId");
      // if('4' === roleId) {
      $('.edit_confirm').attr('disabled', 'true')
      $('.delete_confirm').attr('disabled', 'true')
      // }
    },

    //  获取部门树列表
    getDeptList() {
      getDeptTree().then((res) => {
        this.depData = res.data
      })
    },

    /**
     * 获取部门列表
     */
    getDept() {
      deptList().then((res) => {
        this.deptSelect = res.data
      })
    },

    getToolList() {
      const param = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        param: {}
      }
      if (this.departmentId != '' && this.departmentId != undefined) {
        param.param['departmentId'] = this.departmentId
      }
      materialAll(param).then((res) => {
        this.total = res.data.totalSize
        this.tableData = res.data.content
      })
    },
    //  获取物料类型列表
    getToolTypeList() {
      resourceTypeAll().then((res) => {
        this.toolTypeList = res.data
      })
    },
    // 分页导航
    handleSizeChange(val) {
      this.pageSize = val
      this.getToolList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getToolList()
    },
    //  获取部门列表
    getDept() {
      deptList().then((res) => {
        this.deptSelect = res.data
      })
    },
    seachToolType() {
      // this.$router.push("/ToolTypeManage");
      this.isMaterialTag = !this.isMaterialTag
    },
    // 树节点被点击时调用
    nodeClick(val) {
      const self = this
      // 可将地图的ID设置为树结构的ID，通过点击节点，来切换地图
      // self.v_MyMessage("选择的树分支ID：" + val, "success");
      this.departmentId = val

      this.getToolList()
    },
    // 从excel表格导入数据
    leadingInData: function() {
      // 需要将搜索条件置空，重新刷新列表
      this.editExportVisible = true
    },
    // 阻止upload的自己上传，进行再操作
    // beforeupload(file) {
    //   const fileNameArr = file.name.split('.');
    //   const typeName = fileNameArr[fileNameArr.length - 1].toLocaleLowerCase();
    //   if (typeName != 'xls' && typeName != 'xlsx') {
    //     this.$message("上传文件只能是 xls、xlsx 格式!");
    //     return false;
    //   }
    //   //创建临时的路径来展示图片
    //   let windowURL = window.URL || window.webkitURL;
    //   // this.imgSrc = windowURL.createObjectURL(file);
    //   this.file.append('file',file);
    //   return false;
    // },
    // //确定导入文件
    // saveFileEdit(formName){
    //   this.$refs[formName].validate((valid) => {
    //     console.log(valid);
    //     if (valid) {
    //       let eptType = this.formExp.exportType;
    //       if(eptType == 0){//追加导入
    //         this.$api.staffmanage.adddEpt(this.file,{'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()}).then(res => {
    //           let RES = this.responseUse(res, true);
    //           if(RES){
    //             this.editExportVisible = false;
    //             this.getToolList();
    //             this.getDeptList();
    //           }
    //           this.file = new FormData();
    //         }).catch((error) => {
    //           this.file = new FormData();
    //         });
    //       }else if(eptType == 1){//覆盖导入
    //         this.$api.staffmanage.edotEpt(this.file,{'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()}).then(res => {
    //           let RES = this.responseUse(res, true);
    //           if(RES){
    //             this.editExportVisible = false;
    //             this.getToolList();
    //             this.getDeptList();
    //           }
    //           this.file = new FormData();
    //         }).catch((error) => {
    //           this.file = new FormData();
    //         });
    //       }
    //     }
    //   })
    // },
    // 添加车辆信息
    addData() {
      this.form = { depIdx: '' }
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      if (
        this.departmentId != null &&
        this.departmentId != undefined &&
        this.departmentId != ''
      ) {
        this.form['depIdx'] = Number(this.departmentId)
      }
      this.form = { materialType: 'gl_material' }
      // 需要将搜索条件置空，重新刷新列表
      this.editVisible = true
      this.editEnable = true
      this.dialogStatus = 'addEquipment'
    },

    // 确认添加车辆信息
    saveStaffEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.editEnable) {
            const param = {
              materialType: this.form.materialType,
              materialInfo: this.form.materialInfo,
              tagId: this.form.tagId,
              type: 'material',
              resourceId: this.form.resourceId,
              name: this.form.name,
              workTypeId: this.form.toolTypeId,
              departmentId: this.form.depIdx
            }
            materialSaveEdit(param).then((res) => {
              if (res.code == 200) {
                this.getToolList()
                this.editVisible = false
                this.msgSuccess('成功')
              } else {
                this.msgError('失败')
              }
            })
          } else {
            const param = {
              materialType: this.form.materialType,
              materialInfo: this.form.materialInfo,
              tagId: this.form.tagId,
              resourceId: this.form.resourceId,
              type: 'material',
              idx: this.toolIdx,
              name: this.form.name,
              workTypeId: this.form.toolTypeId,
              departmentId: this.form.depIdx
            }
            materialSaveEdit(param).then((res) => {
              if (res.code == 200) {
                this.getToolList()
                this.editVisible = false
                this.msgSuccess('成功')
              } else {
                this.msgError('失败')
              }
            })
          }
        } else {
          // this.v_MyMessage(this.$t("Notice.verificationFailed"));
          return false
        }
      })
    },
    // 行删除按钮响应
    handleDelete(index, row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', i18n.t('menuManage.title'), {
        confirmButtonText: i18n.t('common.cok'),
        cancelButtonText: this.$i18n.t('operating.cancel'),
        type: 'warning'
      })
        .then(function() {
          const temp = [{ idx: row.idx }]
          return materailDelete(temp)
        })
        .then(() => {
          this.msgSuccess('删除成功')
          this.getToolList()
        })
    },
    // 批量删除
    deleteAll() {
      const length = this.multipleSelection.length
      if (length > 0) {
        this.del_list = this.del_list.concat(this.multipleSelection)
        this.toolIdx = []
        for (let i = 0; i < length; i++) {
          this.toolIdx.push({ idx: this.multipleSelection[i].idx })
        }
        this.$confirm('确定要删除选中内容,删除后数据不可恢复?', i18n.t('menuManage.title'), {
          confirmButtonText: i18n.t('common.cok'),
          cancelButtonText: this.$i18n.t('operating.cancel'),
          type: 'warning'
        })
          .then(() => {
            return materailDelete(this.toolIdx)
          })
          .then(() => {
            this.msgSuccess('删除成功')
            this.getToolList()
          })
      } else {
        this.msgError(this.$t('Notice.selectDeleteObject'))
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
      // console.log(this.multipleSelection);
    },

    // 行编辑按钮响应
    handleEdit(index, row) {
      if (this.$refs['form'] !== undefined) {
        this.$refs['form'].resetFields()
      }
      this.selectIndex = index
      this.toolIdx = row.idx
      this.form = {
        depIdx: row.departmentId,
        name: row.name,
        materialInfo: row.materialInfo,
        toolTypeId: row.workTypeId,
        resourceId: row.resourceId,
        tagId: row.tagId,
        name: row.name
      }
      // 设置编辑框为可见状态
      this.editVisible = true
      this.editEnable = false
      this.dialogStatus = 'editEquipment'
    },
    //  清空搜索的数据
    clearSearchValue() {
      this.searchValue = ''
    },
    // 下载模板
    downloadExp() {
      window.location.href =
        'http:' +
        baseUrl +
        '/resource/getTemplates?token=' +
        Cookie.get('token')
    },
    //  导出
    reportAll() {
      // if (this.departmentId) {
      //   window.location.href =
      //     baseUrl +
      //     "/material/export?departmentId=" +
      //     this.departmentId +
      //     "&token=" +
      //     Cookie.get("token");
      // } else {
      //   window.location.href =
      //       "/material/export?token=" + Cookie.get("token");
      // }

      const urlPath = '/material/export?token=' + Cookie.get('token')
      const filename = 'material_' + (new Date().getTime()) + '.xls'
      downloadFile(urlPath, filename)
    }
  }
}
</script>
<style scoped>
#body {
  /*width: 100%;*/
  /*height: 100%;*/
}
.handle-box >>> .el-input-group__append {
  background-color: #f1a11e;
  color: #fff;
}
.handle-box {
  min-width: 1125px;
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.handle-box * {
  float: left;
}
.handle-box span {
  line-height: 28px;
}

span {
  margin-left: 10px;
  font-size: 13px;
}
.datalist {
  width: 100%;
  min-width: 800px;
}
</style>

